<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\api\model\coupon\CouponType as CouponTypeModel;
use app\api\model\coupon\Coupon as CouponModel;

class Coupon extends Api
{

    protected $noNeedLogin = ['typelists'];
    protected $noNeedRight = ['*'];


    //我的优惠券列表
    public function lists()
    {
        $state = input('state',0);
        $where = ['user_id'=>$this->auth->id];
        if ($state)$where['state'] = $state;
        $list = CouponModel::where($where)->order('createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $this->success('',$list);

    }

    //领取优惠券
    public function receive()
    {
        $coupon_type_id = input('coupon_type_id',0);

        $coupon_type_info = CouponTypeModel::get($coupon_type_id);
        if (!$coupon_type_info)$this->error('优惠券不存在');
        $coupon_model = new CouponModel();

        $data = [
            'coupon_type_id'=>$coupon_type_id,
            'user_id'=>$this->auth->id,
            'coupon_type_module'=>$coupon_type_info['module'],
            'at_least'=>$coupon_type_info['at_least'],
            'money'=>$coupon_type_info['money'],
            'end_time'=>$coupon_type_info['end_use_time'],
            'state'=>1
        ];
        $res = $coupon_model->save($data);

        $this->success('');
    }

    //领券中心
    public function typelists()
    {
        $list = CouponTypeModel::where('end_use_time','>',time())
            ->order('createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $this->success('',$list);
    }


}